/**@author Jason 吕建辉
 * @data 2018-04-07
 * @描述：模板组件采用 layui-2.2.6 操作手册可参考管饭文档
 */
//提取弹窗组件为公共
var layer;
var dictClass;
layui.use(['table', 'layer', 'form'], function () {
    var table = layui.table, form = layui.form;
    layer = layui.layer;
    var tableIns = table.render({
        id: 'table',
        elem: '#table',
        url: '/rbac/dict/list',
        where: $('#searchFrom').containerJson(),
        method: 'get', //如果无需自定义HTTP类型，可不加该参数
        request: pageRequest,
        response: pageResponse,
        page: pagenation,
        cellMinWidth: 60,//全局定义常规单元格的最小宽度
        cols: [[
            {
                field: 'type',
                title: '字典类型',
                align: 'center',
                templet: function (d) {
                    return formatDictClass(d.type);
                }
            }, {
                field: 'code',
                title: '字典编码',
                align: 'center'
            }, {
                field: 'value',
                title: '字典编码值',
                align: 'center'
            }, {
                field: 'status',
                title: '字典状态',
                align: 'center',
                templet: function (d) {
                    return formatterStatus(d.status);
                }
            }, {
                fixed: 'right',
                title: '操作',
                align: 'center',
                toolbar: '#toolbar'
            }
        ]]
    });
    // 绑定操作
    var $2 = layui.$, active = {
        reset: function () {//重置
            clearSearch();
        },
        addDict: function () {//新增字典
            $('#addOrUpdateDict').form('clear');
            openForm('addOrUpdateDict', false);
        },
        addDictClass: function () {//新增类型
            $('#addOrUpdateDictClass').form('clear');
            openForm('addOrUpdateDictClass', true);
        }
    };
    $2('.layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    //监听 新增/编辑 表单提交
    form.on('submit(addOrUpdateDict)', function (data) {
        commitDictForm(tableIns);
    });
    form.on('submit(addOrUpdateDictClass)', function (data) {
        commitDictClassForm(tableIns);
    });
    //监听 查询表单提交
    form.on('submit(search)', function (data) {
        reloadTable(tableIns, data.field);
    });
    //监听 开关按钮
    form.on('switch(status)', function (data) {
        this.checked ? $(this).val(1) : $(this).val(0);
    });
    //表格最后一列操作按钮监听
    table.on('tool(table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            deleteById(data.id, tableIns);
        } else if (obj.event === 'edit') {
            $('#addOrUpdateDict').form('load', data);
            $('#type').val(data.type);
            $('#status').val(data.status);
            form.render('select');//渲染下拉框，必须加，不然不起作用
            openForm('addOrUpdateDict', false);
        }
    });
});

//清空查询条件
function clearSearch() {
    $('.layui-input').val("");
}

//打开表单
function openForm(formId, isClass, tableIns) {
    var height = '70%';
    if (isClass) {
        height = '50%';
    }
    layer.open({
        type: 1,
        title: '字典操作',
        shadeClose: true,
        skin: 'layui-layer-rim',
        anim: 2,
        shade: 0.3,
        maxmin: true,
        area: ['50%', height],
        content: $('#' + formId),//用id时 ，type 必须 =1
        btn: ['提交'],
        yes: function (i) {
            if (isClass) {
                commitDictClassForm(tableIns);
            } else {
                commitDictForm(tableIns);
            }
        }
    });
}

//字典表单
function commitDictForm(tableIns) {
    var data = $('#addOrUpdateDict').serializeJson();
    var url = '/rbac/dict/add';
    if (data.id) {
        url = '/rbac/dict/update'
    }
    commitForm(url, data, tableIns);
}

//字典类型
function commitDictClassForm(tableIns) {
    var data = $('#addOrUpdateDictClass').serializeJson();
    var url = '/rbac/dict/class/add';
    if (data.id) {
        url = '/rbac/dict/class/update'
    }
    commitForm(url, data, tableIns);
}

function commitForm(url, data, tableIns) {
    $.ajax({
        url: url,
        data: data,
        method: 'post',
        success: function (res) {
            if (res.flag) {
                layer.msg('处理成功', {time: 2000}, function () {
                    reloadTable(tableIns);
                });
            } else {
                layer.msg(res.msg, {time: 2000});
            }
        }, error: function () {
            layer.msg('请求失败', {time: 2000});
        }
    });
}

function deleteById(id, obj) {
    layer.confirm('真的删除行么', function (index) {
        $.ajax({
            url: '/rbac/dict/delete',
            method: 'post',
            data: {
                id: id
            },
            success: function (res) {
                if (res.flag) {
                    layer.close(index);
                } else {
                    layer.msg(res.msg, {time: 2000})
                }
                reloadTable(obj)
            }
        });

    });
}

function reloadTable(tableIns, data) {
    tableIns.reload({
        page: {curr: 1},
        where: data
    });
    return false;//防止页面刷新
}

$(document).ready(function () {
    initData();
});

function initData() {
    $.ajax({
        url: '/rbac/dict/class/all',
        method: 'get',
        async: false,
        success: function (res) {
            if (res.flag) {
                dictClass = res.data;
                $.each(res.data, function (index, val) {
                    var option = $('<option value="' + val.id + '">' + val.name + '</option>');
                    $('#s_type,#type').append(option);
                });
            }
        }
    });
}

function formatDictClass(value) {
    var str = '';
    if (value) {
        $.each(dictClass, function (index, val) {
            if (val.id == value) {
                str = val.name;
            }
        });
    }
    return str;
}

function formatterStatus(value) {
    if (1 == value) {
        return "有效";
    }
    return "无效";
}